using System;
using System.Linq;

namespace UMS.Data
{
    public abstract class Entity<TSubType> where TSubType : Entity<TSubType>, new()
    {
        public Guid Id { get; set; }

        public static TSubType Create()
        {
            TSubType newEntity = new TSubType { Id = Guid.NewGuid() };
            Repository.Default().Add(newEntity);
            return newEntity;
        }

        public void Save()
        {
            if (Repository.Default().Exists<TSubType>(x => x.Id == Id))
                Repository.Default().Update((TSubType)this);
            else
                Repository.Default().Add((TSubType)this);
        }

        public void Delete()
        {
            Repository.Default().Delete<TSubType>(Id);
        }

        public static TSubType Find(Guid id)
        {
            return Repository.Default().Single<TSubType>(id);
        }

        public static IQueryable<TSubType> All()
        {
            return Repository.Default().All<TSubType>();
        }
    }
}